package com.zhao.dota.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhao.dota.common.contant.CommonConst;
import com.zhao.dota.mapper.BanPickMapper;
import com.zhao.dota.model.BanPick;
import com.zhao.dota.model.Hero;
import com.zhao.dota.service.BanPickService;
import com.zhao.dota.service.HeroService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class BanPickServiceImpl extends ServiceImpl<BanPickMapper, BanPick> implements BanPickService {

    @Resource
    private HeroService heroService;

    @Override
    public int saveList(List<BanPick> list) {
        int count = 0;
        for (BanPick banPick : list) {
            Hero hero = heroService.getById(banPick.getHeroId());
            if (hero == null) {
                continue;
            }
            banPick.setHeroName(hero.getName());
            banPick.setHeroLocalizedName(hero.getLocalizedName());
            LambdaQueryWrapper<BanPick> query = Wrappers.lambdaQuery(BanPick.class).eq(BanPick::getMatchId, banPick.getMatchId())
                    .eq(BanPick::getOrderNum, banPick.getOrderNum());
            BanPick old = getOne(query);
            if (old == null) {
                count += baseMapper.insert(banPick);
            } else {
                BeanUtil.copyProperties(banPick, old, CommonConst.IGNORE_NULL_VALUE);
                count += baseMapper.updateById(old);
            }
        }
        return count;
    }

    @Override
    public List<BanPick> findByMatchId(Integer matchId) {
        LambdaQueryWrapper<BanPick> query = Wrappers.lambdaQuery(BanPick.class).eq(BanPick::getMatchId, matchId)
                .orderByAsc(BanPick::getOrderNum);
        return list(query);
    }
}
